using System;
using System.Threading;
using System.IO;

namespace bOS.DB
{
	/// <summary>
	/// Descrizione di riepilogo per Counter.
	/// </summary>
	public class Counter
	{
		static Mutex mtxProgressive;
		long lCounter;
		public string sFileName;

		public string FileName 
		{
			get { return sFileName;}
		}

		public Counter(string sFile)
		{
			mtxProgressive = new Mutex();
			this.sFileName = sFile;

			// cerca il file da cui prendere il progressivo per la generazione delle istanze
			if ( File.Exists(this.sFileName)) 
			{
				// Open the file to read from.
				using (StreamReader sr = File.OpenText(this.sFileName)) 
				{
					string s = "";
					while ((s = sr.ReadLine()) != null) 
					{
						lCounter = System.Int32.Parse(s);
					}
				}
			}
			else
			{
				// Create a file to write to.
				using (StreamWriter sw = File.CreateText(this.sFileName)) 
				{
					sw.WriteLine("0");
					lCounter = 0;
				}    
			}
		}

		public long Increment()
		{
			mtxProgressive.WaitOne();

			long lProgressiveTemp=lCounter;
			lProgressiveTemp++;
					
			try
			{
				//loading
				using (StreamWriter sw = File.CreateText(this.sFileName)) 
				{
					sw.WriteLine(lProgressiveTemp);
					lCounter = lProgressiveTemp;
				}    
			}
			catch ( System.Exception)
			{
				lProgressiveTemp = 0;
			}
					
			mtxProgressive.ReleaseMutex();

			return lCounter;
		}
	}


}
